package cc.cc4414.cc02.chat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import cc.cc4414.cc02.chat.VO.FriendVO;
import cc.cc4414.cc02.chat.VO.GroupVO;
import cc.cc4414.cc02.chat.VO.MessageSendVO;
import cc.cc4414.cc02.chat.entity.Friend;
import cc.cc4414.cc02.chat.entity.GroupUser;
import cc.cc4414.cc02.chat.entity.Message;
import cc.cc4414.cc02.chat.entity.MessageSend;
import cc.cc4414.cc02.chat.repository.FriendRepository;
import cc.cc4414.cc02.chat.repository.GroupUserRepository;
import cc.cc4414.cc02.chat.repository.MessageRepository;
import cc.cc4414.cc02.chat.repository.MessageSendRepository;
import cc.cc4414.cc02.chat.service.MessageSendService;
import cc.cc4414.cc02.core.constant.RedisConsts;
import cc.cc4414.cc02.core.util.JsonUtils;
import cc.cc4414.cc02.core.webSocket.WebSocket;
import cc.cc4414.cc02.system.entity.User;

/**
 * @author cc 2018年10月4日
 */
@Service
public class MessageSendServiceImpl implements MessageSendService {

	@Autowired
	private MessageSendRepository messageSendRepository;

	@Autowired
	private MessageRepository messageRepository;

	@Autowired
	private FriendRepository friendRepository;

	@Autowired
	private GroupUserRepository groupUserRepository;

	@Autowired
	private WebSocket webSocket;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public List<FriendVO> friendList(Long userId) {
		List<FriendVO> friendVOs = new ArrayList<FriendVO>();
		List<Friend> friends = friendRepository.findByUserIdAndState(userId, 1);
		for (Friend friend : friends) {
			FriendVO friendVO = new FriendVO();
			friendVO.setId(friend.getFriendId());
			friendVO.setName(friend.getFriendNickname());
			Integer count = messageSendRepository.countBySenderIdAndReceiverIdAndReceiverTypeAndIdGreaterThan(
					friend.getFriendId(), userId, 1, friend.getLastMessageSendId());
			friendVO.setNewMessageNumber(count);
			friendVOs.add(friendVO);
		}
		return friendVOs;
	}

	@Override
	public List<GroupVO> groupList(Long userId) {
		List<GroupVO> groupVOs = new ArrayList<GroupVO>();
		List<GroupUser> groupUsers = groupUserRepository.findByUserId(userId);
		for (GroupUser groupUser : groupUsers) {
			GroupVO groupVO = new GroupVO();
			groupVO.setId(groupUser.getGroupId());
			groupVO.setName(groupUser.getGroupName());
			Integer count = messageSendRepository.countByReceiverIdAndReceiverTypeAndIdGreaterThan(
					groupUser.getGroupId(), 2, groupUser.getLastMessageSendId());
			groupVO.setNewMessageNumber(count);
			groupVOs.add(groupVO);
		}
		return groupVOs;
	}

	@Override
	public void send(User sender, Long receiverId, String msg, Integer receiverType) {
		Message message = new Message();
		message.setType(1);
		message.setContent(msg);
		Message saveMessage = messageRepository.save(message);
		MessageSend messageSend = new MessageSend();
		messageSend.setTime(new Date());
		messageSend.setMessageId(saveMessage.getId());
		messageSend.setSenderId(sender.getId());
		messageSend.setSenderNickname(sender.getNickname());
		messageSend.setReceiverId(receiverId);
		messageSend.setReceiverType(receiverType);
		messageSendRepository.save(messageSend);
		// websocket发送消息
		MessageSendVO messageSendVO = new MessageSendVO();
		BeanUtils.copyProperties(messageSend, messageSendVO);
		messageSendVO.setContent(msg);
		if (receiverType.equals(1)) {
			readMessage(sender.getId(), receiverId, messageSend.getId(), receiverType);
			if (stringRedisTemplate.hasKey(RedisConsts.ONLINE + receiverId)) {
				webSocket.sendMessage(JsonUtils.format(messageSendVO), receiverId);
			}
		}
		if (receiverType.equals(2)) {
			List<GroupUser> groupUsers = groupUserRepository.findByGroupId(receiverId);
			for (GroupUser groupUser : groupUsers) {
				if (stringRedisTemplate.hasKey(RedisConsts.ONLINE + groupUser.getUserId())) {
					webSocket.sendMessage(JsonUtils.format(messageSendVO), groupUser.getUserId());
				}
			}
		}
	}

	@Override
	public List<MessageSendVO> getMessage(Long userId, Long id, int start, int size, int type) {
		List<MessageSendVO> messageSendVOs = new ArrayList<MessageSendVO>();
		List<MessageSend> messageSends = null;
		if (type == 1) {
			messageSends = messageSendRepository.findFriendMessageSend(id, userId, start, size);
		} else if (type == 2) {
			messageSends = messageSendRepository.findGroupMessageSend(id, start, size);
		}
		// 查询出每条消息的内容。这里使用jpa所以是遍历查询的，之后版本使用mybatis，一次性查出来所以数据
		for (MessageSend messageSend : messageSends) {
			MessageSendVO messageSendVO = new MessageSendVO();
			BeanUtils.copyProperties(messageSend, messageSendVO);
			Message message = messageRepository.findById(messageSend.getMessageId()).get();
			messageSendVO.setContent(message.getContent());
			messageSendVOs.add(messageSendVO);
		}
		// 如果查询了最新的消息，则修改关系表中最后一条已读消息的id
		if (start == 0 && messageSendVOs.size() > 0) {
			readMessage(userId, id, messageSendVOs.get(0).getId(), type);
		}
		return messageSendVOs;
	}

	@Override
	public void readMessage(Long userId, Long id, Long messageSendId, int type) {
		if (type == 1) {
			Friend friend = friendRepository.findByUserIdAndFriendId(userId, id);
			friend.setLastMessageSendId(messageSendId);
			friendRepository.save(friend);
		} else if (type == 2) {
			GroupUser groupUser = groupUserRepository.findByGroupIdAndUserId(id, userId);
			groupUser.setLastMessageSendId(messageSendId);
			groupUserRepository.save(groupUser);
		}
	}

}
